MATLAB Pi Programming Sandbox
This is an example of working in MATLAB continuing from our classroom example with our classic pi case.
This is presented in "notebook" form which lets you share the results of your work with people who don't have the [rather expensive] MATLAB license and more importantly lets us "serve" this document online as an HTML web document. R has a similer function when you use the commecial (free versions available) of R-Studio and also the Jupyter notebook tools.
The "grey" areas below are MATLAB code. The not-grey (white) areas are text comments and also model output (you can tell by the difference in the fonts). [Also inside the grey "code" area are comments shown in green with the "%" signs.]
This includes some extras such as tying the errors between π and the estimated values we calculate to the number of significant figures using the Scarborough from the "Errors" Lecture.
We also will demonstrate a more detailed form of text output where you can control the number of significant figures.
If you haven't had a formal computer programming class don't panic here. From Lecture 2 (Pseudocode), you saw that programming structures in different languages tend to have a similar "look-n-feel" or at least are marginally intuitive. Try to follow along.
And away we go!
Normaly you start by descrining what you are going to do. It also sometimes helps to cite any literature you are using.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Test program to show the relationship between significant figures
% and error
%
% Program uses a numerical approximation pi using the "Trapezioidal
% Rule" to estimate pi from your homework #1
%
% Program also uses the Scarborough (1966) formula for linking
% significant figures to percent error error.
%
% Scarborough, J. B., Numerical Mathematical Analysis, 6th ed.,
% Johns Hopkins Press, Baltimore, MD, 1966.
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Let's start by defining what the REAL answer is (or nearly is since
% we are talking about pi
%
PI25DT = pi % lucky for us, pi is an intrinsic value in MATLAB
% that is already in double precision
% [ so is the square root of 1 (i and j) ]
%
% in other languates we may need to manually enter values
% for pi
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
In your homework you were asked to do three specific runs through your π pseudocode example in which you had n = 1, 2 and 3. But since this is a computer program, we can run a LOT of iterations on the same general problem, we can do a lot more here. Here we are "only" going to 100 iterations.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% We now will set the total number of iterations that we'll run through
%
% We will actually be calculating PI for a range of iterations starting
% with n=1 and then going all the way through n=nmax
%
nmax = 100; % maximum value of "n" that we'll try'
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Another important step in many programming languates is to set up your variables and arrays in which you are storing your results ahead of time.
Notice after we initialize the first array, all we have to do for the others is "clone" the first one and use a little bit of Math-Fu (basically just multiplying each array by zero) to initialize them too.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% This section creates arrays (or vectors depending on what you want to
% call them for.
%
% The first line we are acutally creating the equivalent of a "Range" that
% have in Matchad Prime. The good news is that MATLAB doesn't treat
% these "range" variables differently than any other array in MATLAB
% (unlike Mathcad)
%
n_storage_array = 1:nmax; % values of "n" can you guess what this does?
pi_storage_array = n_storage_array*0; % initialize our output pi array to zero
e_pi_storage_array = n_storage_array*0; % initialize our output pi error array to zero
s_pi_storage_array = n_storage_array*0; % initialize our output sigfig array to zero
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
As a reminder, this is how we calculated π here in "mathese"
We will attack this by callculating creating Riemann Sums
where
This is basically a Reimann Sum method as illustrated below from your notes.
(and in the code as is with Differential Equations, the traditional single-letter convention for assigning the
is "h" so it's used in the code below.)
To do this, unlike your homework where you start over from scratch each time. We are sneaking in another loop, wrapped around the meat and potatoes of your homework's pseudocode. This will let us collect all of our estiamtes of π.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Loop for a variety of values of "N" like you did in your first homework
% but this time we are doing it more than just 3 times!
for N = 1:nmax
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Pi is approxinated iteratively for N procedural steps.
% The more steps, the closer the estimate of pi approaches
% the true value
%
% And here si the "meat and potatoes" of your Pseudocode homework!
% one major difference is that I'm using little-n (MATLAB is
% "case senstive") rather than "i" since as we'll see later in the
% class, "i" in MATLAB is a shortcut for sqrt(-1).
h = 1.0 / N;
sum = 0.0; % you will have to reset this summing value this everty time.
for n = 1:N
x = h * (n - 0.5);
sum = sum + 4.d0 / (1.d0 + x*x);
end
est_pi = h*sum;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
With this done inside the outer-loop for whatever value of N you are using, you now have a brand new value of π. As N (the number of Reimann Sum Boxes) gets bigger, the smaller the
, and therefore, your estimate of π will be more and more accurate.
And wirth this you can check your value of π with the value that comes with MATLAB whcih for us is our benchmark value . Here we use both a "plain" error and also a percentage error based on the our "benchmark" value of π.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% error of pi is calculated.
%
error = est_pi - PI25DT;
perc_err = error/PI25DT * 100.;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
And here is the Scarborough formula for linking precision error.
A little Algebra- and Calc-2-Fu will "invert" the original formula so that...
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% We used a formula early in teh class to tie error to precision
%
% Scarborough formula for guestimating the percent error as a
% function of the number of significant figures is "inverted"
% so that we're solving for sig figs rather than the percent
% error. Notice also what I have to do with the "log" command.
% in most languates "plain" "log" is the natural log.
%
Sigfig = 2-log10(perc_err*2);
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
And we can now store our values ofπ, error and the guestimated numbner of significant figures we should expect for a given error.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% store our error values in our "back pocket" for the end
%
pi_storage_array(N) = est_pi;
e_pi_storage_array(N) = error;
s_pi_storage_array(N) = Sigfig;
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Here we plot things out to the screen.
Now while most langauges loops and if-then-else blocks will be somewhat intuitive, making nice print formats is ... more passive-agressive from language to language. MATLAB leverages elements of the C-family of languates.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% And now we print out output to the screen. The strange percent
% codes show the look-n-feel of the displayed floating and integer
% values. The "..." lets me continue to the next line to do a
% single command
%
% This use of Fprint follows Savannah's question on how to have more
% control over the format. C-skateers may recognize the formating
% a following C computer language conventions.
%
% Your onlie help should have a description of this command here...
% https://www.mathworks.com/help/simulink/slref/fprintf.html
%
% The output specific C-formating guidance can be found here...
% https://www.mathworks.com/help/MATLAB/MATLAB_prog/formatting-strings.html
%
fprintf('n= %4.0i, est_pi= %15.12f, Error=%11.8f, %%Error= %11.8f%%, Estimated SF=%3.1f \n', ...
n, est_pi, error, perc_err, Sigfig);
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
end
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
Finally we can make some plots. While in Mathcad the graphing process is Mouse-and-Menu centered. MATLAB is written as a series of commands.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% Some simple plots (including log, semilog and traditional linear plots)
%
figure; % new figure
semilogx(n_storage_array, pi_storage_array); % make a plot with log on the x
title('Iterative Calculation of Pi'); % you will get docked if you
xlabel('Total Number of Iterations (n)'); % don't label your graph
ylabel('Estimated Value of Pi'); % axes and title them.
figure;
loglog(n_storage_array, e_pi_storage_array); % this time it's a log-log
title('Iterative Calculation of Pi');
xlabel('Total Number of Iterations (n)');
ylabel('Error of Estimated Value of Pi');
figure;
plot(n_storage_array, s_pi_storage_array); % and finally a plain old plot
title('Iterative Calculation of Pi');
xlabel('Total Number of Iterations (n)');
ylabel('Approximate Significant Figures in Estimation');
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
So to conclude, don't worry if you couldn't follow this through the first time. As with walking through pseudo-code it takes practice.
We'll officially start working with MATLAB towards the close of the semester.